<script setup>
/**
 * & 文件引入区域
 */
// import 'vant/lib/index.css';
import { showDialog } from "vant";
import { useI18n } from "vue-i18n";
import router from "@/router";
import { onMounted, reactive, ref, nextTick } from "vue";
import { TimePicker } from "vant";
import { useUseStore } from "@/stores/user";
import { useIndexStore } from "@/stores/indexStore";
import { countryList } from "@/data/countryList";
import { useRoute } from "vue-router";

import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";

import {
  getThirdDistrictList,
  getSecondDistrictList,
  getFourthDistrictList,
} from "@/server/api/BuyerData";
import {
  applyShop,
  piIdImageUp,
  shopImageUp,
  physicalStoreImageUp,
  shopImageGet
} from "@/server/api/applyShop";
import {
  getShopInfoById,
  getShopCategoryTopList,
  getShopCategorySecList,
  updateShopApi,
} from "@/server/api/shopApi";

import { ToastFun } from "@/hook/toast";
import { OpenChildrenPage } from "@/hook/routerHandle";
//地图
import { initMap, getLocation } from "@/utils/mapHandle";
import Tip from "@/components/Pengyq/Tip.vue";
/**
 * & 注册区
 */

/**
 * & 变量声明区
 */
const route = useRoute();
const { t } = useI18n();


//付款方式
const payMent = [
  {
    label: t("newAdd.half"),
    value: "50%",
  },
  {
    label: t("newAdd.realmoney"),
    value: "money",
  },
  {
    label: t("newAdd.picoin"),
    value: "PI",
  },
  {
    label: "GCV",
    value: "GCV",
  },
];
//隐藏弹窗
const showPicker = ref(false);
//提示弹窗的翻译
let title = ref("");
title.value = t("me.PersonalPosting.shop.tip.title");
let message = ref("");
message.value = t("me.PersonalPosting.shop.tip.message");
let ok = ref("");
ok.value = t("me.PersonalPosting.shop.tip.ok");
// 回显数组
let shopImg = ref([]); // 回显店铺封面图的数组
const actionImg = ref([]); // 回显店铺实景图的数组
const acceptQrcode = ref([]) //回显付款图片
// 传给后端的图片路径
let idImgReq; // 发送到后端的piId图片
let actionImgReq = []; // 发送到后端的店铺实景图的数组
const acceptQrcodeReq = ref() // 传给后端的图片路径

const uploadedImage = ref(""); // 存储上传的图片
const showCropper = ref(false); // 控制裁剪工具的显示
const cropperInstance = ref(null); // 存储 Cropper 实例
let initialReq = ref({});
// 组件控制
let cateTopShow = ref(false); // 控制一级分类选择弹框显示隐藏
let cateSecShow = ref(false); // 控制二级分类选择弹框显示隐藏

// 地区选择
let countryCon = ref(); // 控制选中的国家样式
let provinceCon = ref(); // 控制选中的国家样式
let cityCon = ref(); // 控制选中的国家样式
let regionCon = ref(null); // 控制选中的区县样式

let secDisList = ref(); // 二级行政区数据列表
let thdDisList = ref(); // 三级行政区数据列表
let fthDisList = ref(); // 三级行政区数据列表

let show = ref(false); // 控制地区选择弹框显示隐藏
let changeView = reactive({
  isCountry: false, // 控制国家设置面板的显示隐藏
  isProvince: false, // 控制省份设置面板的显示隐藏
  isCity: false, // 控制城市设置面板的显示隐藏
  isRegion: false, // 控制区县设置面板的显示隐藏
});
let addSelect = ref(""); // 选择的地区
let addDetail = ref(""); // 绑定详细地址

// 获取实体店分类列表
let ShopCategoryTop = ref(); // 一级分类
let ShopCategorysec = ref(); // 二级分类
let categoryPid = ref(); // 请求二级分类列表id
let categorySecId = ref(); // 控制点击二级分类样式
let categoryTitle = ref(); // 选择的分类标题

const useIndex = useIndexStore();
let baseUrl = useUseStore().ing;
const id = ref(null);
id.value = route.query.id;
// 修改实体店接口请求体
const shopFormReq = ref({
  address: null, // 地址
  categoryId: null, // 选择二级分类id
  endTime: null, //闭店时间
  localhostLatitude: null, // 纬度
  localhostLongitude: null, // 经度
  phone: null, // 绑定店铺电话
  piratio: null, //付款方式
  shopId: null,
  shopImagList: [], //实景
  deleteImageList: [],
  qrcode: null, // 扫描二维码获取的id
  shopIntroduce: null, // 绑定店铺详情信息
  shopName: "", // 绑定店铺名称
  startTime: null, //开店时间
  tagList: "",
  userImage: null,
});
// 地区码id
let regionId = reactive("");
shopFormReq.value.shopId = id.value;
//获取经纬度
const getLongitudeAndLatitude = async () => {
  ToastFun("Loading", {
    duration: 2000 // 2秒后自动关闭
  });
  const res = await getLocation();
  //赋值
  shopFormReq.value.localhostLongitude = res.longitude; //经度
  shopFormReq.value.localhostLatitude = res.latitude; //纬度
  ToastFun(t("pay.success2"), {})
};
/**
 * & 函数区
 */
/**
 * 申请实体店接口
 * applyShopFun
 *
 * 图片上传三个接口
 * piIdImageUpFun 上传Pi截图接口 到后台审核
 * shopTopImgUpFun 上传封面图接口 到后台审核
 * shopImagsListUpFun 实体店的实景图集合上传接口
 ******/

// 图片上传后的处理逻辑
const handleImageUpload = (file) => {
  const reader = new FileReader();
  reader.onload = () => {
    uploadedImage.value = reader.result; // 将图片预览数据存入 uploadedImage
    showCropper.value = true; // 显示裁剪工具
    nextTick(() => {
      const imageElement = document.querySelector(".cropper-container img");
      if (imageElement) {
        cropperInstance.value = new Cropper(imageElement, {
          aspectRatio: 3 / 3, // 设置裁剪比例为 3x3 正方形
          viewMode: 1,
          // dragMode: "none", // 禁止拖动图片
          autoCropArea: 1, // 自动裁剪
          // cropBoxResizable: false, // 禁止调整裁剪框大小
          movable: false, // 禁止移动裁剪框
        });
      } else {
        console.error("未找到裁剪图片的 img 元素");
      }
    });
  };
  reader.readAsDataURL(file.file);
};

// 确认裁剪
const confirmCrop = async () => {
  if (cropperInstance.value) {
    const croppedCanvas = cropperInstance.value.getCroppedCanvas();
    croppedCanvas.toBlob(async (blob) => {
      const croppedFile = new File([blob], "cropped-image.jpg", {
        type: "image/jpeg",
      });
      try {
        // 调用上传图片的函数并等待响应
        await shopTopImgUpFun(croppedFile);
        // const responseImg = await shopImageGet(response);
        // const imageUrl = { url: responseImg.data.data };
        // shopImg.value = [imageUrl]; // 假设返回的 URL 存储在 response.data 中
        DataSweeperPro();
      } catch (error) {
        console.error("上传出错:", error);
      }
    });
  } else {
    console.error("裁剪实例未初始化");
  }
};


// 取消裁剪
const cancelCrop = () => {
  showCropper.value = false; // 隐藏裁剪工具
  uploadedImage.value = ""; // 清空预览图片
  shopImg.value = []; // 清空上传图片
  if (cropperInstance.value) {
    cropperInstance.value.destroy(); // 销毁裁剪工具实例
    cropperInstance.value = null;
  }
};

const DataSweeperPro = () => {
  showCropper.value = false; // 隐藏裁剪工具
  cropperInstance.value.destroy(); // 销毁裁剪工具实例
  uploadedImage.value = ""; // 清空预览图片
};


const onConfirm = ({ selectedOptions }) => {
  showPicker.value = false;
  shopFormReq.value.piratio = selectedOptions[0]?.value;
};

const reset = async () => {
  shopImg.value = []
  acceptQrcode.value = []
  actionImg.value = []
  getShopInfo(route.query.id)
  ToastFun(t("pay.success2"), {})
}

const updateShopFun = async () => {

  // 拼接地区和详细地址
  shopFormReq.value.address = addSelect.value + " / " + addDetail.value;
  if (addDetail.value === "" || addSelect.value === "") {
    ToastFun("show", { msg: t("me.addNewAddress.addressError") });
    return false;
  }
  if (shopFormReq.value.piratio == "" || shopFormReq.value.shopIntroduce == "" || shopFormReq.value.shopName == "" || shopFormReq.value.categoryId == "") {
    ToastFun("show", { msg: t("me.addNewAddress.deficientData") });
    return false;
  }
  if (shopFormReq.value.phone == "") {
    ToastFun("show", { msg:t("me.addNewAddress.PhoneError") });
    return false;
  }
  if (acceptQrcode.value == "" || shopImg.value == "" || actionImg.value.length == 0) {
    ToastFun("show", { msg:t("me.PersonalPosting.shop.imgTips5") });
    return false;
  }
  ToastFun("Loading", { duration: 5000 });

  let acceptQrcodeFile = acceptQrcode.value[0];
  if (acceptQrcodeFile.file) {
    try {
      let formData = new FormData();
      formData.append("multipartFile", acceptQrcodeFile.file);
      let { data } = await physicalStoreImageUp(formData);
      if (data.code === 500) {
        showDialog({
          title: '提示',
          message: `${data.msg}`,
        }).then(() => {
          // on close
        });
        acceptQrcodeFile.status = 'failed';
        acceptQrcodeFile.message = '上传失败';
        acceptQrcode.value = acceptQrcode.value.filter(item => item !== acceptQrcodeFile);
        return;
      }
      if (data.code === 200) {
        acceptQrcodeFile.status = 'success';
        acceptQrcodeFile.message = '上传成功';
        shopFormReq.value.qrcode = data.data;
      }
    } catch (error) {
      console.error('上传异常:', error);
      acceptQrcode.value = acceptQrcode.value.filter(item => item !== acceptQrcodeFile);
    }
  }
  if (topImgFormData.has("multipartFile")) {
    try {
      // 调用接口
      ToastFun("Loading", { duration: 0 });
      let { data } = await physicalStoreImageUp(topImgFormData);
      if (data.code === 500) {
        showDialog({
          title: '提示',
          message: `${data.msg}`,
        }).then(() => {
          // on close
        });
        // file.status = 'failed';
        // file.message = '上传失败';
        // shopImg.value = shopImg.value.filter(item => item !== file);
        return;
      }
      if (data.code === 200) {
        // file.status = 'success';
        // file.message = '上传成功';
        shopFormReq.value.userImage = data.data;
        // ToastFun("close", {});
        // return shopFormReq.value.userImage;
      }
    } catch (error) {
      console.error('上传异常:', error);
      // shopImg.value = shopImg.value.filter(item => item !== file);
    }
  }

  const uploadPromises = shopImagsListFiles.value.map(async (file) => {
    file.status = 'uploading';
    file.message = '上传中...';
    const formData = new FormData();
    formData.append("file", file.file);
    try {
      const { data } = await shopImageUp(formData);

      if (data.code === 500) {
        // 上传失败的提示
        showDialog({
          title: '提示',
          message: `${data.msg}`,
        }).then(() => { });
        file.status = 'failed';
        file.message = '上传失败';
        actionImg.value = actionImg.value.filter(item => item !== file);
        return;
      }

      if (data.code === 200) {
        if (!Array.isArray(actionImgReq)) {
          actionImgReq = [];
        }

        // 检查图片是否已存在
        const imageExists = data.data.some(image =>
          actionImgReq.includes(image)
        );

        if (!imageExists) {
          // 如果图片不存在，上传成功
          file.status = 'success';
          file.message = '上传成功';
          shopFormReq.value.shopImagList.push(...data.data);
          //将多个文件分成单个上传 后端却是多个上传...
          file.upPath = data.data[0];
        } else {
          // 如果图片已存在，提示用户
          showDialog({
            title: '提示',
            message: "图片已存在",
          }).then(() => { });
          file.status = 'failed';
          file.message = '图片已存在';
          actionImg.value = actionImg.value.filter(item => item !== file);
        }
      }
    } catch (error) {
      console.error("上传异常:", error);
      file.status = 'failed';
      file.message = '上传异常';
      actionImg.value = actionImg.value.filter(item => item !== file);
    }
  });
  // 处理删除图片
  const deletedImages = findDeletedImages();
  if (deletedImages.length > 0) {
    shopFormReq.value.deleteImageList = deletedImages;
  }
  // 使用 Promise.all 并行处理所有上传请求
  try {
    await Promise.all(uploadPromises);
  } catch (error) {
    console.error("批量上传异常:", error);
  }


  let { data } = await updateShopApi(shopFormReq.value);

  if (data.code == 200) {
    ToastFun("", {});
    history.go(-2); // 跳转到商店管理页面
  } else {
    ToastFun("", {});
  }
};

const findDeletedImages = () => {
  // 找出shopFormReq.value中删除的图片ID
  const deletedImages = [];

  // 比较 shopImagListCode（数组）
  const initialShopImages = initialReq.value.shopImagListCode || [];
  const updatedShopImages = shopFormReq.value.shopImagList || [];
  // 找到 initialReq 中有但 shopFormReq 中没有的图片
  initialShopImages.forEach(imageId => {
    if (!updatedShopImages.includes(imageId)) {
      deletedImages.push(imageId);
    }
  });

  // 比较 qrcodeCode（单个值）
  const initialQrcode = initialReq.value.qrcodeCode;
  const updatedQrcode = shopFormReq.value.qrcode;
  if (initialQrcode && initialQrcode !== updatedQrcode) {
    deletedImages.push(initialQrcode);
  }

  // 比较 userImageCode（单个值）
  const initialUserImage = initialReq.value.userImageCode;
  const updatedUserImage = shopFormReq.value.userImage;
  if (initialUserImage && initialUserImage !== updatedUserImage) {
    deletedImages.push(initialUserImage);
  }

  return deletedImages;
};


//付款码图片
const acceptQrcodeFun = async (file) => {
  file.status = 'success';  // 直接设置为上传成功状态
  file.message = '已选择图片';
  acceptQrcode.value = [file];

};


let topImgFormData = new FormData();
//封面
const shopTopImgUpFun = async (file) => {
  file.status = 'success';
  file.message = '已选择图片';
  topImgFormData.set("multipartFile", file);
};


// const piIdImageUpFun = async (file) => {
//   // 转为formData对象，再传到后端
//   let formData = new FormData();
//   formData.append("multipartFile", file.file);

//   // 调用接口
//   let { data } = await piIdImageUp(formData);

//   idImgReq = data.data;
// };



//实景图
// const shopImagsListUpFun = async (files) => {
//   if (!Array.isArray(files)) {
//     files = [files]; // 将单个文件包装成数组
//   }
//   // 遍历多个文件并上传
//   const uploadPromises = files.map(async (file) => {
//     file.status = 'uploading';
//     file.message = '上传中...';
//     let formData = new FormData();
//     formData.append("file", file.file);

//     try {
//       let { data } = await shopImageUp(formData);

//       if (data.code === 500) {
//         showDialog({
//           title: '提示',
//           message: `${data.msg}`,
//         }).then(() => {
//           // on close
//         });
//         file.status = 'failed';
//         file.message = '上传失败';
//         actionImg.value = actionImg.value.filter(item => item !== file);
//         return;
//       }

//       if (data.code === 200) {
//         if (!Array.isArray(shopFormReq.value.shopImagList)) {
//           shopFormReq.value.shopImagList = [];
//         }
//         // 检查图片是否已存在
//         const imageExists = data.data.some(image => shopFormReq.value.shopImagList.includes(image));
//         if (!imageExists) {
//           file.status = 'success';
//           file.message = '上传成功';
//           file.upPath = data.data[0];
//           shopFormReq.value.shopImagList.push(...data.data); // 添加成功上传的图片
//         } else {
//           showDialog({
//             title: '提示',
//             message: "图片已存在",
//           }).then(() => {
//             // on close
//           });
//           file.status = 'failed';
//           file.message = '图片已存在';
//           actionImg.value = actionImg.value.filter(item => item !== file);
//         }
//       }
//     } catch (error) {
//       console.error("上传店铺图片时出错:", error);
//       file.status = 'failed';
//       file.message = '上传异常';
//       actionImg.value = actionImg.value.filter(item => item !== file);
//     }
//   });

//   // 使用 Promise.all 执行所有的上传请求
//   try {
//     await Promise.all(uploadPromises); // 等待所有上传请求完成
//   } catch (error) {
//     console.error("批量上传异常:", error);
//   }
// };
let shopImagsListFiles = ref([]);
//实景图
const shopImagsListUpFun = async (files) => {
  if (!Array.isArray(files)) {
    files = [files];
    shopImagsListFiles.value.push(...files);
  }
  console.log(shopImagsListFiles.value);

};


const fileDelete = (file, detail) => {
  shopImagsListFiles.value = shopImagsListFiles.value.filter(item => item.objectUrl !== file.objectUrl)
  // console.log(shopImagsListFiles.value);
  if (file.url) {
    // 遍历 actionImgReq，找到对应的 id
    const matchedId = Object.keys(actionImgReq.value).find(id => actionImgReq.value[id] === file.url);
    if (matchedId) {
      // 从 shopImagList 中移除对应的 id
      shopFormReq.value.shopImagList = shopFormReq.value.shopImagList.filter(id => id !== matchedId);
    } else {
      console.warn("未找到对应的图片，无法删除:", file.url);
    }
  } else {
    console.warn("文件没有 URL，无法删除");
  }
};

/**
 * 获取实体店一级分类列表 getShopCateTopListFun
 * 获取实体店二级分类列表 getShopCateSecListFun
 *******/
// 获取实体店一级分类列表
const getShopCateTopListFun = async () => {
  ToastFun("Loading", { duration: 1000 });
  let { data } = await getShopCategoryTopList();

  if (data.code == 200) {
    ToastFun("close", {});

    // 拼接图片路径
    data.data.forEach(
      (item) => (item.categoryImg = baseUrl + item.categoryImg)
    );

    // 暂无飞机分类 过滤
    ShopCategoryTop.value = data.data.filter((item) => item.content != "飞机");
  }

};

// 获取实体店二级分类列表
const getShopCateSecListFun = async (id) => {
  // 控制样式
  categoryPid.value = id;

  // 请求接口
  ToastFun("Loading", { duration: 1000 });
  let { data } = await getShopCategorySecList(id);

  if (data.code == 200) {
    ToastFun("close", {});

    // 图片路径拼接
    data.data.forEach(
      (item) => (item.categoryImg = baseUrl + item.categoryImg)
    );
    ShopCategorysec.value = data.data;

    cateTopShow.value = false; // 隐藏一级分类
    cateSecShow.value = true; // 显示二级分类
  }

};

// 获取用户点击的二级分类id
const getSecCateId = (id, title) => {
  // 控制选择样式
  categorySecId.value = id;
  // 将id放入请求体
  shopFormReq.value.categoryId = id;
  categoryTitle.value = title;

  // 隐藏弹框
  cateSecShow.value = false;
};

// 图片上传超过限制提示
const onOversize = () => {
  ToastFun("show", { msg: t("me.PersonalPosting.item.tips4") });
};

/**
 * 获取地区码方法
 */
// 切换设置面板方法
const changeViewFun = (type) => {
  // 显示弹出层
  show.value = true;

  // 如果是重新点击点击 每次都清空
  if (type == "isCountry") {
    addSelect.value = "";
    regionCon.value = null;
  }

  // 通过遍历将所有的面板隐藏后，再将传入的type对应的面板显示
  for (const key in changeView) changeView[key] = false;
  changeView[type] = true;
};

// 获取二级行政区域列表
const getSecDisListFun = async (id, country) => {
  // 拼接地址
  addSelect.value = addSelect.value + country + " / ";

  countryCon.value = id;
  ToastFun("Loading", { duration: 1000 });

  let { data } = await getSecondDistrictList(id); // 请求接口

  if (data.code == 200) {
    ToastFun("close", {});
    secDisList.value = data.data;

    // 显示省份设置面板
    changeViewFun("isProvince");
  } else {
    ToastFun("", {});
  }
};

// 获取三级行政区域列表
const getThdDisListFun = async (id, province) => {
  if (countryCon.value == "CN") {
    // 拼接地址
    addSelect.value = addSelect.value + province + " / ";

    provinceCon.value = id;
    ToastFun("Loading", { duration: 1000 });

    let { data } = await getThirdDistrictList(id); // 请求接口

    if (data.code == 200) {
      ToastFun("close", {});

      // 显示省份设置面板
      changeViewFun("isCity");
      thdDisList.value = data.data;
    } else {
      ToastFun("", {});
    }
  } else {
    getRegionIdFun(id, province);
  }
};

// 获取四级行政区域列表
const getFthDisListFun = async (id, city) => {
  addSelect.value = addSelect.value + city + " / ";

  ToastFun("Loading", { duration: 1000 });
  let { data } = await getFourthDistrictList(id); // 请求接口

  if (data.code == 200) {
    ToastFun("close", {});

    // 显示省份设置面板
    changeViewFun("isRegion");
    fthDisList.value = data.data;
  } else {
    ToastFun("", {});
  }
};

// 获取地区Id方法
const getRegionIdFun = (id, region) => {
  // 拼接地址
  addSelect.value = addSelect.value + region;

  if (countryCon.value == "CN" && regionCon.value == null) {
    regionCon.value = id;
    getFthDisListFun(id);
  } else {
    // 将地区id赋值给请求体对应字段
    regionId = id;
    // 隐藏弹出层
    show.value = false;
  }
};

//时间选择器展示
const showStart = ref(false);
const showEnd = ref(false);

const sTime = ref(["09", "00"]);
const eTime = ref(["21", "00"]);
shopFormReq.value.startTime = String(sTime.value).replace(",", ":");
shopFormReq.value.endTime = String(eTime.value).replace(",", ":");

const confirmStart = () => {
  showStart.value = false;
  showEnd.value = false;
  shopFormReq.value.startTime = String(sTime.value).replace(",", ":");
  shopFormReq.value.endTime = String(eTime.value).replace(",", ":");
};
//过滤PAIFTWARE这个分类
const countryData = ref(null);
const countryListFilter = () => {
  countryData.value = countryList;
};
onMounted(() => {
  getShopInfo(route.query.id)
  getShopCateTopListFun();
  //提示信息

  //初始化地图，获取经纬度
  initMap();
  // 过滤国家
  countryListFilter();
});

const DefaultPicUrl = () => {
  ToastFun("show", { msg: t("me.PersonalPosting.item.tips4")});
};

const getShopInfo = async (shopId) => {
  const res = await getShopInfoById(shopId)
  initialReq.value = JSON.parse(JSON.stringify(res.data.data));  // 深拷贝
  shopFormReq.value.address = res.data.data.address
  shopFormReq.value.localhostLatitude = res.data.data.localhostLatitude
  shopFormReq.value.localhostLongitude = res.data.data.localhostLongitude
  shopFormReq.value.piratio = res.data.data.piratio
  shopFormReq.value.shopName = res.data.data.shopName
  shopFormReq.value.shopIntroduce = res.data.data.shopIntroduce
  shopFormReq.value.startTime = res.data.data.startTime
  shopFormReq.value.endTime = res.data.data.endTime
  shopFormReq.value.phone = res.data.data.phone
  shopFormReq.value.shopImagList = res.data.data.shopImagListCode;
  shopFormReq.value.userImage = res.data.data.userImageCode
  shopFormReq.value.qrcode = res.data.data.qrcodeCode


  shopImg.value.push({ url: res.data.data.userImage })
  acceptQrcode.value.push({ url: res.data.data.qrcode })
  addSelect.value = res.data.data.address.substring(0, res.data.data.address.lastIndexOf('/')).trim();

  // 方法1：使用 split
  addDetail.value = res.data.data.address.split('/').pop().trim();

  // 方法2：使用 substring 和 lastIndexOf
  addDetail.value = res.data.data.address.substring(res.data.data.address.lastIndexOf('/') + 1).trim();

  categoryTitle.value = res.data.data.categoryId

  shopFormReq.value.categoryId = res.data.data.categoryIdCode
  // 遍历并将每个图片 URL 添加到 actionImg 中
  actionImgReq.value = res.data.data.shopImagList;
  if (res.data.data.shopImagList && Object.keys(res.data.data.shopImagList).length > 0) {
    // 使用 Object.entries() 获取每个键值对
    Object.entries(res.data.data.shopImagList).forEach(([id, url]) => {
      // 将 URL 添加到 actionImg 中
      actionImg.value.push({ url: url });
      // 将键（图片 ID）添加到 actionImgReq 中
    });
  }

}
</script>

<template>
  <!-- 顶部返回按钮 -->
  <div class="top">
    <!-- <TopButton :title="$t('me.PersonalPosting.shop.title')" /> -->
    <TopButton :title="$t('updateStoreInfo.title')" />
  </div>

  <div class="update_Shop">
    <!-- 提示框 -->
    <div v-if="useUseStore().showTip">
      <Tip />
    </div>
    <main>
      <!-- <div class="item qrcode">
        <img
          src="/images/Me/scaner.png"
          alt=""
          :class="['scaner', useIndexStore().isRtl ? 'is_rtl' : '']"
          @click="OpenChildrenPage('/scannerCode', { flag: true })"
        />

        <input
          type="text"
          v-model="useIndex.acceptQrcode"
          :placeholder="$t('me.PersonalPosting.shop.acceptQrcode')"
        />
      </div> -->

      <div class="BueAddress">
        <div class="price_title">
          {{ $t("me.PersonalPosting.shop.address") }}
        </div>


        <div class="list">



          <div class="item addressList">
            <van-field :placeholder="$t('me.PersonalPosting.shop.addressTips')" @click="changeViewFun('isCountry')"
              v-model="addSelect" readonly is-link />
          </div>

          <div class="item inp">
            <input type="text" v-model="addDetail" :placeholder="$t('me.PersonalPosting.shop.addDetailsTips')" />
          </div>
          <div class="location">
            <input class="i1" type="text" v-model="shopFormReq.localhostLongitude"
              :placeholder="$t('me.PersonalPosting.shop.longitude')" />
            <input class="i1" type="text" v-model="shopFormReq.localhostLatitude"
              :placeholder="$t('me.PersonalPosting.shop.Dimensions')" />
            <button class="i1" type="button" @click="getLongitudeAndLatitude">
              {{ $t("longLat") }}
            </button>
          </div>

          <div class="item live_action_img">

            <van-uploader v-model="acceptQrcode" preview-size="40rem" :max-count="1" :after-read="acceptQrcodeFun"
              :max-size="5000 * 1024" @oversize="onOversize" @delete="shopFormReq.qrcode = ''" />
            <div class="tips" v-show="!acceptQrcode.length">
              &nbsp;&nbsp;{{ $t('me.PersonalPosting.shop.acceptQrcode') }}
            </div>
          </div>

          <div class="item live_action_img">
            <span style="color: red; font-size: 23rem">*</span>
            <van-uploader v-model="shopImg" preview-size="40rem" :max-count="1" :after-read="handleImageUpload"
              :max-size="5000 * 1024" @oversize="DefaultPicUrl" @delete="shopFormReq.userImage = ''" />
            <div class="tips" v-show="!shopImg || shopImg.length === 0">
              &nbsp;&nbsp;{{ $t("me.PersonalPosting.shop.imgTips1") }}
            </div>
            <!-- 裁剪工具的模态框 -->
            <div v-if="showCropper" class="cropper-container">
              <div>
                <img ref="cropperImage" :src="uploadedImage" alt="To Crop" />
              </div>
              <div class="cropper-actions">
                <button @click="confirmCrop">裁剪并上传</button>
                <button @click="cancelCrop">取消</button>
              </div>
            </div>
          </div>

          <div class="item live_action_img">
            <span style="color: red; font-size: 23rem">*</span>
            <van-uploader v-model="actionImg" preview-size="40rem" :max-count="8" :after-read="shopImagsListUpFun"
              :max-size="5000 * 1024" @oversize="onOversize" @delete="fileDelete" multiple />
            <div class="tips" v-show="!actionImg.length">
              &nbsp;&nbsp; {{ $t("me.PersonalPosting.shop.imgTips2") }}
            </div>
          </div>

          <div class="item inp">
            <input type="text" v-model="shopFormReq.shopName" :placeholder="$t('me.PersonalPosting.shop.shopName')" />
          </div>

          <div class="item shopDetail">
            <van-field v-model="shopFormReq.shopIntroduce" rows="2" type="textarea" maxlength="150"
              :placeholder="$t('me.PersonalPosting.shop.shopDetails')" show-word-limit autosize />
          </div>

          <div class="item inp cateSelect" @click="cateTopShow = true">
            <div class="title">
              {{
                categoryTitle || $t("me.PersonalPosting.item.selectCategory")
              }}
            </div>
            <van-icon name="arrow-down" size="16rem" />
          </div>

          <!-- 付款方式 -->
          <div class="item inp">
            <input style="outline: none" type="text " v-model="shopFormReq.piratio" readonly="true"
              :placeholder="$t('newAdd.payment')" @click="showPicker = true" clearable="true" />
            <van-popup v-model:show="showPicker" round position="bottom">
              <van-picker :columns="payMent" @confirm="onConfirm" @cancel="showPicker = false" confirm-button-text="✔️"
                cancel-button-text="✖️" :columns-field-names="{ text: 'label', value: 'value' }"></van-picker>
            </van-popup>
          </div>

          <!-- 营业时间 -->
          <div class="item inp">
            <input readonly v-model="shopFormReq.startTime" :placeholder="$t('storePost.on')"
              @click="showStart = true" />
            <van-time-picker v-model="sTime" title="⌚" v-show="showStart" confirm-button-text="✔️"
              cancel-button-text="✖️" @confirm="confirmStart" @cancel="showStart = false" />
          </div>
          <div class="item inp">
            <input readonly v-model="shopFormReq.endTime" :placeholder="$t('storePost.off')" @click="showEnd = true" />
            <van-time-picker v-model="eTime" title="⌚" v-show="showEnd" confirm-button-text="✔️" cancel-button-text="✖️"
              @confirm="confirmStart" @cancel="showEnd = false" />
          </div>

          <div class="item inp">
            <input type="number" v-model="shopFormReq.phone" :placeholder="$t('me.PersonalPosting.shop.phone')" />
          </div>
        </div>
      </div>
    </main>

    <div class="footer_button">
      <button @click="reset">{{ $t("me.PersonalPosting.reset") }}</button>

      <button @click="updateShopFun">
        {{ $t("me.PersonalPosting.confirm") }}
      </button>
    </div>

    <!-- 地区选择弹窗 -->
    <van-popup :style="{ height: '92%' }" v-model:show="show" position="bottom" class="popup" round>
      <!-- 关闭弹窗按钮 -->
      <div class="btn">
        <img @click="show = false" src="/images/Home/语言切换面板按钮.png" alt="" />
      </div>

      <div class="setUpView country" v-if="changeView.isCountry">
        <!-- <div class="select">
          <span>智能识别国家</span>
          <span class="selected">加拿大</span>
        </div> -->
        <div class="content">
          <div :class="['item', countryCon == item.countryCode ? 'con' : '']"
            @click="getSecDisListFun(item.countryCode, item.countryEName)" v-for="(item, i) in countryData" :key="i">
            <span>{{ item.countryEName }}</span>
            <img :src="`/images/countryImg/${item.img}`" alt="" />
          </div>
        </div>
      </div>

      <div class="setUpView province" v-if="changeView.isProvince">
        <div class="content">
          <div :class="['item', provinceCon == item.countryId ? 'con' : '']"
            @click="getThdDisListFun(item.countryId, item.name)" v-for="(item, i) in secDisList" :key="i">
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>

      <div class="setUpView city" v-if="changeView.isCity">
        <div class="content">
          <div :class="['item', cityCon == item.countryId ? 'con' : '']"
            @click="getRegionIdFun(item.countryId, item.name)" v-for="(item, i) in thdDisList" :key="i">
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>

      <div class="setUpView region" v-if="changeView.isRegion">
        <div class="content">
          <div :class="['item', cityCon == item.countryId ? 'con' : '']"
            @click="getRegionIdFun(item.countryId, item.name)" v-for="(item, i) in fthDisList" :key="i">
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 一级分类选择弹窗 -->
    <van-popup v-model:show="cateTopShow" :style="{ height: '50%' }" class="catePopup" position="bottom" round>
      <div class="list">
        <div :class="['item', categoryPid == item.categoryId ? 'con' : '']"
          @click="getShopCateSecListFun(item.categoryId)" v-for="item in ShopCategoryTop" :key="item.categoryId">
          <span>{{ $t(`shopFirCate.${item.content}`) }}</span>

          <img v-if="item.categoryImg" :src="item.categoryImg" alt="" />
        </div>
      </div>
    </van-popup>

    <!-- 二级分类选择弹窗 -->
    <van-popup v-model:show="cateSecShow" class="catePopup" round position="bottom" :style="{ height: '50%' }">
      <div class="list">
        <div :class="['item', categorySecId == item.categoryId ? 'con' : '']" v-if="ShopCategorysec.length > 0"
          @click="getSecCateId(item.categoryId, item.content)" v-for="item in ShopCategorysec" :key="item.categoryId">
          <span>{{ $t(`shopFirCate.${item.content}`) }}</span>

          <img v-if="item.categoryImg" :src="item.categoryImg" alt="" />
        </div>
        <div v-else><van-empty description="空" /></div>
      </div>
    </van-popup>
  </div>
  <!--初始化地图框架，必须!! -->
  <div id="container"></div>
</template>

<style lang="scss" scoped>
.top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 20;
}

@mixin fileBox {
  padding: 12rem 12rem 4rem;
  background-color: #f5f5f5;
  border-radius: 6rem;

  :deep(.van-uploader__upload) {
    background-color: #999999;
  }

  :deep(.van-uploader) {
    height: 100%;
  }
}

.update_Shop {
  background-color: #ffffff;
  padding: 60rem 16rem 60rem;
  font-size: 14rem;

  max-height: 100vh;

  box-sizing: border-box;
  overflow: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  main {
    padding-top: 14rem;

    .qrcode {
      display: flex;
      align-items: center;
      font-size: 12rem;
      line-height: 16rem;
      color: #999;
      padding: 12rem 12rem;
      background: #f5f5f5;

      .scaner {
        width: 28rem;
        height: 28rem;
        margin-right: 16rem;

        &.is_rtl {
          margin-left: 16rem;
          margin-right: 0;
        }
      }

      input {
        width: 280rem;
        background: transparent;
      }
    }

    .addPrice {
      .price_title {
        line-height: 35rem;
        color: #000;
        font-size: 20rem;
        font-weight: 500;
        border-bottom: 1rem solid #ccc;
      }

      .file {
        margin-top: 10rem;
        @include fileBox;
      }
    }

    .BueAddress {
      margin-top: 20rem;

      .price_title {
        line-height: 35rem;
        color: #000;
        font-size: 20rem;
        font-weight: 500;
        border-bottom: 1rem solid #ccc;
      }

      >.list {
        padding-top: 12rem;
        font-weight: 400;

        .location {
          display: flex;
          background: #f5f5f5;
          margin-bottom: 12rem;
          height: 50rem;
          align-items: center;

          >input {
            background: transparent;
            width: 110px;
          }

          >button {
            width: 110px;
            height: 30rem;
            background-color: transparent;
            /* 设置圆角半径 */
            // border-radius: 20px;
            /* 设置边框样式和颜色 */
            border: 1px solid;
            /* 设置阴影效果 */
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
          }
        }

        .item {
          margin-bottom: 16rem;

          background: #f5f5f5;
          border-radius: 4rem;
        }

        .inp {
          font-size: 12rem;
          line-height: 16rem;
          color: #999;
          padding: 12rem 12rem;
          background: #f5f5f5;
          border-radius: 4rem;

          >input {
            width: 100%;
            background: transparent;
            color: #444;
            border: none;
            outline: none;
            font-size: 12rem;
          }
        }

        >.addressList {
          >.van-cell {
            background: #f5f5f5;
            border-radius: 4rem;
            padding: 14rem 12rem;

            :deep(.van-badge__wrapper) {
              transform: rotate(90deg);
            }
          }
        }

        >.live_action_img {
          @include fileBox;
          position: relative;

          >.tips {
            width: max-content;
            height: max-content;
            margin: auto;

            position: absolute;
            top: 0;
            bottom: 0;
            left: 60rem;

            font-size: 12rem;
            font-weight: 400;
            line-height: 16rem;
            color: #999;
          }
        }

        >.shopDetail {
          >.van-cell {
            background: transparent;
          }
        }

        >.cateSelect {
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }

  .footer_button {
    display: flex;
    justify-content: space-around;

    button {
      flex: 1;

      color: #642e8eff;
      background-color: #fff;
      height: 40rem;
      line-height: 40rem;
      border-radius: 20rem;
      text-align: center;
      border: 1rem solid;

      &:nth-of-type(2) {
        color: #fff;
        background-color: #642e8eff;
        margin-left: 12rem;
      }
    }
  }

  :deep(.popup) {
    border-radius: 12rem 12rem 0rem 0rem;
    overflow-y: scroll;
    background: #f5f5f5;

    &::-webkit-scrollbar {
      display: none;
    }

    .btn {
      display: flex;
      justify-content: center;
      padding: 16rem 0 28rem;
      background: #f5f5f5;

      position: sticky;
      top: 0;
      z-index: 10;

      >img {
        width: 37rem;
        height: 8rem;
      }
    }

    .setUpView {
      z-index: 10;
      width: 100%;

      .select {
        padding: 12rem 0 12rem 12rem;
        background: #fff;

        display: flex;
        align-items: center;

        span {
          font-size: 14rem;
          line-height: 20rem;
          font-weight: 500;

          &.selected {
            font-size: 12rem;
            font-weight: 400;
            line-height: 16rem;
            margin-left: 12rem;
          }
        }
      }

      .content {
        font-size: 14rem;

        >.item {
          padding: 12rem;
          background: #fff;

          display: flex;
          align-items: center;
          justify-content: space-between;

          >img {
            width: 35rem;
          }

          &.con {
            background: #fbfbfb;
            font-weight: 700;
          }
        }
      }
    }
  }
}

.catePopup {
  background: #000;

  >.list {
    padding: 20rem;
    min-height: 100%;
    box-sizing: border-box;

    >.item {
      padding: 18rem 16rem;
      font-size: 20rem;
      line-height: 20rem;
      font-weight: 500;
      color: #999;

      display: flex;
      justify-content: space-between;
      align-items: center;

      >img {
        width: 30rem;
        height: 30rem;
      }

      border: 1rem solid #ccc;
      border-radius: 8rem;

      margin-bottom: 15rem;

      &.con {
        border-color: #642e8e;
        color: #8966a3;
        font-weight: 700;
      }
    }
  }
}

.location {
  display: flex;
  background: #f5f5f5;
  margin-bottom: 12rem;
  height: 50rem;
  align-items: center;

  >input {
    background: transparent;
    width: 110px;
  }

  >button {
    width: 110px;
    height: 30rem;
    background-color: transparent;
    /* 设置圆角半径 */
    // border-radius: 20px;
    /* 设置边框样式和颜色 */
    border: 1px solid;
    /* 设置阴影效果 */
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
  }
}

.cropper-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.cropper-actions {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
}

.cropper-actions button {
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}
</style>